<template>
  <div class="box">
    <div class="role-manage">
      <el-button
        type="primary"
        @click="addRole()"
        size="small"
        class="margin-bottom20"
        >新增角色</el-button
      >
      <el-table
        :data="roleList"
        :show-header="false"
        ref="multipleTable"
        @row-click="selectRole"
        border
        id="sort"
        highlight-current-row
      >
        <el-table-column label="名称">
          <template slot-scope="scope">
            <div class="role">
              <div class="role-name">
                <el-input
                  v-model="inputValue"
                  v-if="scope.row.isEdit"
                  size="small"
                  @blur="inputConfirm(scope.row)"
                  @click.stop.native
                ></el-input>
                <span v-if="!scope.row.isEdit">{{ scope.row.label }}</span>
              </div>
              <div>
                <i class="el-icon-edit" @click.stop="edit(scope.row)"></i>
                <i
                  class="el-icon-delete  margin-right20 margin-left20"
                  @click.stop="deleteHandle(scope.row)"
                ></i>
                <i
                  class="el-icon-copy-document"
                  @click.stop="copyHandle(scope.row)"
                ></i>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="auth-manage">
      <el-tree
        :data="data"
        node-key="id"
        default-expand-all
        show-checkbox
        :expand-on-click-node="false"
        @check-change="handleCheckChange"
        ref="tree"
      ></el-tree>
      <el-button
        size="small"
        type="primary"
        @click="save()"
        class="margin-top20"
        >保存</el-button
      >
    </div>
    <el-dialog
      title="新增角色"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="500px"
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import Sortable from 'sortablejs'
import { manageTree, tableUpdate, tableInsert } from '@/api/api'
import {
  distributePermission,
  getRoleAndPermission,
  copyPermissions,
  addRole
} from '@/api/user'
import RoleManage from '../organize-structure/role-manage'
export default {
  name: 'user-power',
  components: { RoleManage },
  data () {
    return {
      roleList: [],
      role_id: '',
      inputValue: '',
      data: [],
      roleRelatedList: [],
      selectList: [],
      visible: false,
      form: {
        name: ''
      },
      formRules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      }
    }
  },
  activated () {
    this.getRoleList()
  },
  // mounted () {
  // this.rowDrop()
  // },
  methods: {
    async getAuthorityList () {
      let res = await manageTree({
        tableName: 'nice_permission_tree'
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        let array = [data.data]
        let response = []
        this.queryList(array, response)
        this.data = this.$deepcopy(response)
        this.getRoleAndPermission()
      }
    },
    async getRoleList () {
      let res = await manageTree({
        tableName: 'nice_role'
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        if (data.data.hasOwnProperty('child')) {
          this.roleList = data.data.child.map(ele => {
            return {
              label: ele.role_name,
              value: ele.id,
              isEdit: false
            }
          })
          this.role_id = this.role_id ? this.role_id : this.roleList[0].value
          this.getAuthorityList()
        }
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async getRoleAndPermission () {
      let res = await getRoleAndPermission({})
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.roleRelatedList = data.data.list
        let arr = this.roleRelatedList.filter(item => {
          return this.role_id === item.role_id
        })
        this.queryRelation(this.data, arr)
        this.roleList.forEach((ele, index) => {
          if (ele.value === this.role_id) {
            this.$refs.multipleTable.setCurrentRow(
              this.$refs.multipleTable.data[index]
            )
          }
        })
        this.$refs.tree.setCheckedNodes(this.selectList)
      } else {
        this.$message.error(res[1].msg)
      }
    },
    queryRelation (tdata, list) {
      tdata.forEach(ele => {
        list.forEach(item => {
          if (ele.id === item.permission_id) {
            this.selectList.push(ele)
          }
          if (ele.children && ele.children.length) {
            this.queryRelation(ele.children, list)
          }
        })
      })
    },
    queryList (tdata, list) {
      if (tdata.length) {
        tdata.forEach((ele, index) => {
          list[index] = {
            label: ele.node_name,
            id: ele.node_id,
            isEdit: false
          }
          let arr = []
          this.queryList(ele.child, arr)
          list[index].children = arr
        })
      }
    },
    selectRole (item) {
      this.role_id = item.value
      this.selectList = []
      let arr = this.roleRelatedList.filter(ele => {
        return this.role_id === ele.role_id
      })
      this.queryRelation(this.data, arr)
      this.$refs.tree.setCheckedNodes(this.selectList)
    },
    addRole () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
      })
    },
    // 拖拽角色
    // rowDrop () {
    // const tbody = document.querySelector('.el-table__body-wrapper tbody')
    // const _this = this
    // Sortable.create(tbody, {
    //   onEnd ({ newIndex, oldIndex }) {
    // 拖动完成
    // const currRow = _this.list.splice(oldIndex, 1)[0]
    // _this.list.splice(newIndex, 0, currRow)
    //   }
    // })
    // },
    async save () {
      if (!this.selectList.length) {
        this.$message.error('请选择权限！')
        return false
      }
      let res = await tableInsert([
        {
          table_name: 'nice_role_permission',
          list: this.selectList.map(ele => {
            return {
              permission_id: ele.id,
              role_id: this.role_id
            }
          })
        }
      ])
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.getRoleList()
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async inputConfirm (item, id) {
      if (!this.inputValue) {
        this.$message.error('请输入角色名称！')
        return false
      }
      if (this.inputValue.length > 16) {
        this.$message.error('只能输入16个字符！')
        return false
      }
      let res = await tableUpdate([
        {
          table_name: 'nice_role',
          update: [
            {
              role_name: this.inputValue
            }
          ],
          where: [
            {
              id: item.value
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.getRoleList()
      } else {
        this.$message.error(res[1].msg)
      }
    },
    edit (item) {
      this.inputValue = item.label
      this.roleList.forEach(ele => {
        if (ele.value === item.value) {
          item.isEdit = true
        } else {
          ele.isEdit = false
        }
      })
    },
    deleteHandle (row) {
      this.$confirm('确定删除操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeRole(row)
        })
        .catch(() => {})
    },
    async removeRole (row) {
      let res = await tableUpdate([
        {
          table_name: 'nice_role',
          update: [{ enable: '1' }],
          where: [{ id: row.value }]
        },
        {
          table_name: 'nice_role',
          update: [{ enable: '1' }],
          where: [{ parent: row.value }]
        }
      ])
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.getRoleList()
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async copyHandle (item) {
      let res = await copyPermissions({
        'nice_role.role_name': item.label,
        'nice_role.parent': '1',
        'nice_role_permission.permission_id': item.value
      })
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.getRoleList()
      } else {
        this.$message.error(res[1].msg)
      }
    },
    handleCheckChange (data, checked, indeterminate) {
      if (checked) {
        if (!this.selectList.find(obj => obj.id === data.id)) {
          this.selectList.push(data)
        }
      } else {
        this.selectList.forEach((ele, index) => {
          if (ele.id === data.id) {
            this.selectList.splice(index, 1)
          }
        })
      }
    },
    dataFormSubmit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.submit()
        }
      })
    },
    async submit () {
      let res = await addRole({
        'nice_role.role_name': this.form.name,
        'nice_role.parent': '1'
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.getRoleList()
        this.visible = false
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  .role-manage {
    width: 500px;
    height: 560px;
    overflow: auto;
    .role {
      display: flex;
      justify-content: space-between;
      .role-name {
        flex: 1;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .auth-manage {
    flex: 1;
    margin-left: 5%;
    margin-top: 50px;
    text-align: right;
  }
}
</style>
